package com.gtw.pattern.simple.lazyfactory;

import com.gtw.pattern.simple.ConcreteProduct1;
import com.gtw.pattern.simple.ConcreteProduct2;
import com.gtw.pattern.simple.Product;

import java.util.HashMap;
import java.util.Map;

/**
 * 一个对象被消耗完,并不立刻释放,工厂类保持其初始状态,等待再次被调用
 * 此方式可以扩展,如限制某一个产品的最大实例化数,可以判断Map中已有数量来判断
 */
public class ProductCreator {

    private static final Map<String, Product> PRODUCT_MAP = new HashMap<String, Product>();
    public static synchronized Product createProduct(String type){
        Product product = null;
        if(PRODUCT_MAP.containsKey(type)){
            product = PRODUCT_MAP.get(type);
        }else {
            if("product1".equals(type)){
                product = new ConcreteProduct1();
            }else {
                product = new ConcreteProduct2();
            }
            PRODUCT_MAP.put(type, product);
        }
        return product;
    }
}
